package com.woniuxy.house.filter;

import com.woniuxy.house.entity.JwtToken;
import com.woniuxy.house.exception.NotValidException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author baobo
 * @date 2022-08-29-12:26
 */
@Slf4j
public class ApiJwtAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
	/**
	 * 匹配路径
	 * @param defaultFilterProcessesUrl
	 */
	public  ApiJwtAuthenticationFilter(String defaultFilterProcessesUrl) {
		super("/api/user/*");
	}

	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
				log.info("request.getRequestURI():{}",request.getRequestURI());
		//获取jwt
		String jwt = request.getHeader("jwt");
		if(jwt==null||"".equals(jwt)){
			throw new NotValidException("jwtToken不存在");
		}
		//创建未认证的jwt
		JwtToken jwtToken=new JwtToken(jwt);
		Authentication authenticate = this.getAuthenticationManager().authenticate(jwtToken);
		return authenticate;
	}
}
